package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.dto.ReadBehaviorDto;
import com.heima.behavior.entity.ApReadBehavior;
import com.heima.behavior.entity.UpdateArticleMessage;
import com.heima.behavior.service.IReadService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ReadServiceImpl implements IReadService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private KafkaTemplate kafkaTemplate;
    @Value("${topic.read_behavior}")
    private String ReadTopic;





//    阅读行为的介绍
    @Override
    public ResponseResult saveRead(ReadBehaviorDto dto) {

//        首先是构造一个ReadBehavior对象
        ApReadBehavior apReadBehavior=new ApReadBehavior();
        User user = AppThreadLocalUtil.get();
        if(user!=null){
            apReadBehavior.setUserId(user.getUserId());
        }else {
            apReadBehavior.setEquipmentId(dto.getEquipmentId());
        }
        apReadBehavior.setArticleId(dto.getArticleId());
        apReadBehavior.setReadDuration(dto.getReadDuration());
        apReadBehavior.setPercentage(dto.getPercentage());
        apReadBehavior.setLoadDuration(dto.getLoadDuration());
        apReadBehavior.setCreatedTime(new Date());
//        格根据文章id和用户（设备）id查询
        Query query=new Query();
        if(user!=null){
            query.addCriteria(Criteria.where("userId").is(dto.getUserId()));

        }else {
            query.addCriteria(Criteria.where("equipmentId").is(dto.getEquipmentId()));
        }
        query.addCriteria(Criteria.where("articleId").is(dto.getArticleId()));
        ApReadBehavior one = mongoTemplate.findOne(query, ApReadBehavior.class);
//        判断如果布存在添加
        if(one==null){
            mongoTemplate.save(apReadBehavior);
            sendMessage(dto);

        }else{
            Update update=new Update();
//            one.setCount(one.getCount()+1);  反面教材  不具有原子性
//            inc 具有原子性  如果在一个时间点多个访问督导的次数可能一样
            update.inc("count");
            update.set("readDuration",dto.getReadDuration());
            update.set("percentage",dto.getPercentage());
            update.set("loadDuration",dto.getLoadDuration());
            update.set("updatedTime",new Date());
            mongoTemplate.updateFirst(query,update,ApReadBehavior.class);
            sendMessage(dto);
        }


        return ResponseResult.okResult();
    }

//    发送到kafka
    private void sendMessage(ReadBehaviorDto dto){
        UpdateArticleMessage message=new UpdateArticleMessage();
        message.setType(0);
        message.setAdd(1);
        message.setArticleId(dto.getArticleId());
        String value = JSON.toJSONString(message);
        kafkaTemplate.send(ReadTopic,value);

    }
}
